<template>
  <div id="app">
    <transition-group tag="div" leave-active-class="animate__animated animate__hinge position-absolute">
      <cart-item
        v-for="(cart, index) in cartList"
        :key="cart.id"
        v-bind="cart"
        @change="cartList.splice(index, 1, $event)"
        @delete="cartList.splice(index, 1)"
        @scroll-start="onScrollStart"
      />
    </transition-group>

    <cart-footer v-bind="cartTotal" @all-check="onAllCheck" ref="cart-footer" />
  </div>
</template>

<script>
import CartFooter from "./components/CartFooter.vue";
import CartItem from "./components/CartItem.vue";
import MyConfirm from "./plugins/confirm/MyConfirm.vue";

const cartList = [
  {
    id: 1,
    title: "【新人专享】按摩颈椎 泰国93%天然乳胶枕",
    img: "/img/01.webp",
    price: 179.0,
    num: 1,
    checked: true,
  },
  {
    id: 2,
    title: "T30无限吸尘器【配件】",
    img: "/img/02.webp",
    price: 159.0,
    num: 2,
    checked: false,
  },
  {
    id: 3,
    title: "免撕抽取，放心存放 一次性食品保鲜袋",
    img: "/img/03.webp",
    price: 12.9,
    num: 2,
    checked: true,
  },
  {
    id: 4,
    title: "多功能人体工学转椅",
    img: "/img/04.webp",
    price: 1228.0,
    num: 2,
    checked: true,
  },
];

export default {
  name: "App",
  components: {
    CartItem,
    CartFooter,
    MyConfirm,
  },
  data() {
    return {
      cartList,
    };
  },
  computed: {
    cartTotal() {
      return this.cartList.reduce(
        (prev, cart) => {
          return {
            totalNum: prev.totalNum + (cart.checked ? cart.num : 0),
            totalPrice:
              prev.totalPrice + (cart.checked ? cart.num * cart.price : 0),
            allChecked: prev.allChecked && cart.checked,
          };
        },
        {
          totalNum: 0,
          totalPrice: 0,
          allChecked: true,
        }
      );
    },
  },
  methods: {
    onAllCheck($event) {
      this.cartList.forEach((cart) => (cart.checked = $event));
    },
    // 对cart-item触发的scroll-start事件的回调函数
    onScrollStart($event) {
      // 比较直观的写法，就是通过this.$children获取到所有的子组件实例，调用子组件实例中的scrollTo方法  ，让所有的子组件滚回原点
      // 但是这种写法 代码耦合度太高，不好
      // console.log(this.$children)
      // const arr = [...this.$children]
      // const index = arr.findIndex(item => item === $event)

      // arr.splice(index, 1)

      // arr.forEach(item => item.scrollTo && item.scrollTo())

      // 更好的写法 父组件 也触发一个自定义事件，通知绑定了该事件的子组件，告诉子组件是哪个实例开始了滚动，再由子组件自己内部来处理这个事件
      this.$emit("cart-item-scroll", $event);
    },
  },
  mounted() {
    console.log(this.$refs["cart-footer"]);

    // this.$on('cart-item-scroll', () => {
    //   this.$children.
    // })
  },
};
</script>

<style lang="scss"></style>
